using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public delegate void BirdEvent();

public class BirdControll : MonoBehaviour
{
    RectTransform BirdRectTransform;

    //上升的速度
    [SerializeField]
    private float flyUpSpeed = 0.2F;
    [SerializeField]
    private float flyUpReduction = 0.2F;
    private float currentFlyDistance = 0;

    //下落的速度
    [SerializeField]
    private float fallG = 0.2F;
    [SerializeField]
    private float initFallSpeed;

    private float fallSpeed = 0;
    private float currentFallDistance = 0;

    //障碍物
    [SerializeField]
    private BlockGenerator blockGenerator;

    //碰撞判定框
    [SerializeField]
    private RectTransform CollideBox;

    //死亡状态
    public bool alive = false;

    //定义事件
    public event BirdEvent BirdDie;

    // Start is called before the first frame update
    void Start()
    {
        BirdRectTransform = gameObject.transform as RectTransform;

        //在OnGameStart中注册匿名方法设置存活状态
        GlobalEventManager.OnGameStart += () => { alive = true; };

        //在OnGameRestart中注册重置鸟位置的方法
        GlobalEventManager.OnGameRestart += ResetBird;

        //在OnGameOver中注册匿名方法设置存活状态
        GlobalEventManager.OnGameOver += () => { alive = false; };
    }

    // Update is called once per frame
    void Update()
    {
        //获取输入，在按键按下后设置上升的持续时间。如果游戏没有在运行，游戏开始运行。
        if (Input.GetMouseButtonDown(0) && alive)
        {
            currentFlyDistance = flyUpSpeed;
            FlyUp();
        }

        //游戏运行时，处理鸟的移动
        if (alive)
        {
            BirdMove();
        }

        //每帧检测碰撞
        if (alive && collide())
        {
            BirdDie();
        }
    }

    //鸟移动控制
    void BirdMove()
    {
        //根据上升的距离，判断鸟上升还是下落
        if (currentFlyDistance > 0)
        {
            FlyUp();
        }
        else
        {
            Fall();
        }
    }

    //控制鸟在一段时间内持续向上移动
    void FlyUp()
    {
        currentFallDistance = 0;
        fallSpeed = initFallSpeed;

        //currentFlyUpSpeed -= Input.GetKeyDown(flyKey) ? 0 : flyG*Time.deltaTime;
        currentFlyDistance -= flyUpReduction*Time.deltaTime;

        currentFlyDistance = currentFlyDistance < 0 ? 0 : currentFlyDistance;
        Vector2 originPos = BirdRectTransform.anchoredPosition;
        Vector2 newPos = new Vector2(originPos.x, originPos.y += currentFlyDistance*Time.deltaTime);
        BirdRectTransform.anchoredPosition = newPos;
        EdgeLimit();
    }

    //函数，控制鸟下落
    void Fall()
    {
        fallSpeed += fallG * Time.deltaTime;
        currentFallDistance += fallSpeed * Time.deltaTime;
        Vector2 originPos = BirdRectTransform.anchoredPosition;
        Vector2 newPos = new Vector2(originPos.x, originPos.y -= currentFallDistance*Time.deltaTime);
        BirdRectTransform.anchoredPosition = newPos;
        EdgeLimit();
    }

    //边界限制
    void EdgeLimit()
    {
        RectTransform parentCanvas = GetComponentInParent<RectTransform>();
        float localScreenHeight = Screen.height / parentCanvas.lossyScale.y;
        if(BirdRectTransform.anchoredPosition.y < -localScreenHeight / 2)
        {
            Vector2 originPos = BirdRectTransform.anchoredPosition;
            Vector2 newPos = new Vector2(originPos.x, -localScreenHeight/2);
            BirdRectTransform.anchoredPosition = newPos;
            BirdDie();
        }
        else if(BirdRectTransform.anchoredPosition.y > localScreenHeight / 2)
        {
            Vector2 originPos = BirdRectTransform.anchoredPosition;
            Vector2 newPos = new Vector2(originPos.x, localScreenHeight / 2);
            BirdRectTransform.anchoredPosition = newPos;
        }
    }

    //重置鸟的位置
    public void ResetBird()
    {
        gameObject.transform.localPosition = new Vector3(0, 0, 0);
        alive = false;
    }

    //遍历障碍物并检测碰撞
    bool collide()
    {
        List<GameObject> allBlocks = blockGenerator.allBlocks;
        if(allBlocks.Count <= 0)
        {
            return false;
        }



        foreach(GameObject block in allBlocks)
        {
            RectTransform blockUp = block.GetComponent<BlockControll>().blockUp;
            RectTransform blockDown = block.GetComponent<BlockControll>().blockDown;

            if (collideTwo(CollideBox,blockUp) || collideTwo(CollideBox,blockDown))
            {
                return true;
            }
        }

        return false;
    }

    //两个物体间的碰撞检测
    bool collideTwo(RectTransform first, RectTransform second )
    {
        Vector2 firstPosition = first.position;
        float firstWidth = first.rect.width * first.lossyScale.x;
        float firstHeight = first.rect.height * first.lossyScale.y;

        Vector2 secondPosition = second.position;
        float secondWidth = second.rect.width * second.lossyScale.x;
        float secondHeight = second.rect.height * second.lossyScale.y;

        if(firstPosition.x + firstWidth/2 > secondPosition.x - secondWidth/2 && firstPosition.x - firstWidth/2 < secondPosition.x + secondWidth / 2)
        {
            //横向相交后，判断纵向相交
            if(firstPosition.y + firstHeight / 2 > secondPosition.y - secondHeight / 2 && firstPosition.y - firstHeight / 2 < secondPosition.y + secondHeight / 2)
            {
                return true;
            }
        }
        return false;
    }
}
